package com.njwb.Util;

import com.njwb.pojo.Bill;
import com.njwb.pojo.Supplier;
import com.njwb.pojo.SupplierBill;
import com.njwb.pojo.Users;
import org.apache.ibatis.session.SqlSession;

import javax.swing.table.TableModel;
import java.awt.*;
import java.sql.Date;
import java.util.ArrayList;
import java.util.function.Function;

public class UtilService {
    private Io io = new Io();

    // ===================== 公共执行方法 =====================
    private <R> R execute(Function<UtilDaoMapper, R> function) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UtilDaoMapper mapper = sqlSession.getMapper(UtilDaoMapper.class);
            return function.apply(mapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private <R> R executeWithCommit(Function<UtilDaoMapper, R> function) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UtilDaoMapper mapper = sqlSession.getMapper(UtilDaoMapper.class);
            R result = function.apply(mapper);
            sqlSession.commit();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // ===================== 用户相关 =====================
    public String logn(String username, String password, int role) {
        return execute(mapper -> {
            Users user = mapper.findByUsername(username);
            if (user == null) return "用户不存在";
            Users loginUser = mapper.findByUsernameAndPassRole(username, password, role);
            if (loginUser == null) return "用户名或密码错误 / 角色不匹配";
            return "登录成功";
        });
    }

    public ArrayList<Users> getAllUsers() {
        ArrayList<Users> list = execute(mapper -> mapper.getAllUsers());
        return list != null ? list : new ArrayList<>();
    }

    public ArrayList<Users> getUsersByUsername(String name) {
        ArrayList<Users> list = execute(mapper -> mapper.getUsersByUsername(name));
        return list != null ? list : new ArrayList<>();
    }

    public boolean addUser(String username, String password, String gender, int age, String phone, String address, int role) {
        Integer re = executeWithCommit(mapper -> {
            if (mapper.findByUsername(username) != null) return 0;
            return mapper.addUser(username, password, gender, age, phone, address, role);
        });
        return re != null && re > 0;
    }

    public boolean updateUser(int id, String username, String password, String gender, int age, String phone, String address, int role) {
        Integer re = executeWithCommit(mapper -> mapper.updateUser(id, username, password, gender, age, phone, address, role));
        return re != null && re > 0;
    }

    public boolean deleteUser(int id) {
        Integer re = executeWithCommit(mapper -> mapper.deleteUser(id));
        return re != null && re > 0;
    }

    // ===================== 供应商相关 =====================
    public ArrayList<Supplier> getAllSupplier() {
        ArrayList<Supplier> list = execute(mapper -> mapper.getAllSupplier());
        return list != null ? list : new ArrayList<>();
    }

    public ArrayList<Supplier> getSupplierByName(String name) {
        ArrayList<Supplier> list = execute(mapper -> mapper.getSupplierByName(name));
        return list != null ? list : new ArrayList<>();
    }

    public boolean addSupplier(String name, String description, String contact_person, String phone, String address) {
        Integer re = executeWithCommit(mapper -> mapper.addSupplier(name, description, contact_person, phone, address));
        return re != null && re > 0;
    }

    public boolean updateSupplier(int id, String name, String description, String contact_person, String phone, String address) {
        Integer re = executeWithCommit(mapper -> mapper.updateSupplier(id, name, description, contact_person, phone, address));
        return re != null && re > 0;
    }

    public boolean deleteSupplier(int supplier_id) {
        Integer re = executeWithCommit(mapper -> {
            if (mapper.countSupplierById(supplier_id) == 0) return 0;
            mapper.deleteBillsBySupplierId(supplier_id);
            return mapper.deleteSupplier(supplier_id);
        });
        return re != null && re > 0;
    }

    // ===================== 账单相关 =====================
    public ArrayList<Bill> getAllBill() {
        ArrayList<Bill> list = execute(mapper -> mapper.getAllBill());
        return list != null ? list : new ArrayList<>();
    }

    public ArrayList<Bill> getBill(String product_name, Boolean is_paid) {
        ArrayList<Bill> list = execute(mapper -> mapper.getBill(product_name, is_paid));
        return list != null ? list : new ArrayList<>();
    }

    public boolean addBill(String product_name, int quantity, String unit, Double amount,
                           Boolean is_paid, String supplier_name, String product_description, Date bill_time) {
        Integer re = executeWithCommit(mapper -> {
            Integer supplier_id = mapper.getSupplierIdByName(supplier_name);
            if (supplier_id == null) return 0;
            return mapper.addBill(product_name, quantity, unit, amount, is_paid, supplier_id, product_description, bill_time);
        });
        return re != null && re > 0;
    }

    public boolean modifyBill(int bill_id, String product_name, int quantity, String unit, Double amount,
                              Boolean is_paid, String supplier_name, String product_description, Date bill_time) {
        Integer re = executeWithCommit(mapper -> {
            Integer supplier_id = mapper.getSupplierIdByName(supplier_name);
            if (supplier_id == null) return 0;
            return mapper.modifyBill(bill_id, product_name, quantity, unit, amount, is_paid, supplier_id, product_description, bill_time);
        });
        return re != null && re > 0;
    }

    public boolean deleteBill(int bill_id) {
        Integer re = executeWithCommit(mapper -> mapper.deleteBill(bill_id));
        return re != null && re > 0;
    }

    public ArrayList<SupplierBill> getSupplierStatistics() {
        ArrayList<SupplierBill> list = execute(mapper -> mapper.getSupplierStatistics());
        return list != null ? list : new ArrayList<>();
    }

    // ===================== 导入导出 =====================
    public void exportTableToTxt(Component parent, TableModel tableModel) {
        io.exportTableToTxt(parent, tableModel);
    }

    public void importSupplier(Component parent) {
        io.importSupplier(parent, this);
    }
}
